import Vue from 'vue'
import VueRouter from 'vue-router'
import Store from '../store'

const Home = () => import('../view/Home.vue')

Vue.use(VueRouter)


// 下列三行代码是方式路由跳转时点击多次报出错误，进行错误抛出
//获取原型对象上的push函数
const originalPush = VueRouter.prototype.push
//修改原型对象中的push方法
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}


const routes = [
  {
    path: '/',
    redirect: '/home'
  },
  {
    path: '/home',
    name: 'Home',
    meta: {
      ifShowTabbar: true
    },
    component: Home,
    children: [
      {
        path: 'popup',
        name: 'MyPopup',
        component: () => import('../view/MyPopup.vue')
      }
    ]
  },
  {
    path: '/topic',
    name: 'Topic',
    meta: {
      ifShowTabbar: true
    },
    component: () => import('../view/Topic.vue')
  },
  {
    path: '/category',
    name: 'Category',
    meta: {
      ifShowTabbar: true
    },
    component: () => import('../view/Category.vue'),
    children: [
      {
        path: 'popup',
        name: 'CMyPopup',
        component: () => import('../view/MyPopup.vue')
      }
    ]
  },  
  {
    path: '/cart',
    name: 'Cart',
    meta: {
      ifShowTabbar: true
    },
    component: () => import('../view/Cart.vue')
  },  
  {
    path: '/user',
    name: 'User',
    meta: {
      ifShowTabbar: true
    },
    component: () => import('../view/User.vue')
  },
  {
    path: '/productdetail/:id',
    name: 'ProductDetail',
    component: () => import('../view/ProductDetail.vue')
  },
  {
    path: '/channel',
    name: 'Channel',
    component: () => import('../view/Channel.vue')
  },
  {
    path: '/brand/:id',
    name: 'Brand',
    component: () => import('../view/Brand.vue')
  },
]

const router = new VueRouter({
  routes,
})



// 全局的导航守卫 - 前置导航守卫 - 路由拦截
// 如果是跳转到购物车页面，那么需要先判断是否登录(token)，
// 如果是跳转到其他任何页面，就直接next()
// to代表即将进入的路由
// from代表即将离开的路由
// next(),每一个导航守卫必须至少搭配一个next()

router.beforeEach((to, from, next) => {
  let token = localStorage.getItem('usertoken')
  if (to.path === '/cart') {
    if (token) {
      next(); //这个next只针对去往/cart的
    } else {
      // 因为路由组件没有this，所以只能在vue的原型上找
      Vue.prototype.$toast.loading({
        message: '请先登录...',
        forbidClick: true,
      });
      setTimeout(() => {
        next('/user')
        // 修改vuex中的ifgoBack
        Store.commit("changeIfgoBack", true);
      }, 800)
    }
    return;
  }
  // 这个next是适配所有路由的
  next()
})



export default router